from rest_framework import serializers
from .models import Warehouse, Inventory, InventoryRecord, PurchaseOrder, PurchaseOrderItem
from products.serializers import ProductSerializer
from products.models import Product
from decimal import Decimal, InvalidOperation

class WarehouseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Warehouse
        fields = ['id', 'name', 'location', 'type', 'capacity', 'manager', 'status', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

class InventorySerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)
    warehouse_name = serializers.CharField(source='warehouse.name', read_only=True)
    unit = serializers.CharField(source='product.unit', read_only=True)
    
    class Meta:
        model = Inventory
        fields = ['id', 'product', 'product_name', 'warehouse', 'warehouse_name', 
                 'current_stock', 'min_stock', 'max_stock', 'unit',
                 'purchase_date', 'expiry_date', 'status', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

class InventoryRecordSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='inventory.product.name', read_only=True)
    warehouse_name = serializers.CharField(source='inventory.warehouse.name', read_only=True)
    operator_name = serializers.CharField(source='operator.username', read_only=True)
    source_warehouse_name = serializers.CharField(source='source_warehouse.name', read_only=True)
    target_warehouse_name = serializers.CharField(source='target_warehouse.name', read_only=True)
    
    class Meta:
        model = InventoryRecord
        fields = ['id', 'inventory', 'product_name', 'warehouse_name', 'operation_type', 
                 'quantity', 'operator', 'operator_name', 'source_warehouse', 
                 'source_warehouse_name', 'target_warehouse', 'target_warehouse_name', 
                 'related_order', 'note', 'created_at']
        read_only_fields = ['id', 'created_at']


class PurchaseOrderItemSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)
    unit = serializers.CharField(source='product.unit', read_only=True)
    warehouse_name = serializers.CharField(source='warehouse.name', read_only=True)
    
    class Meta:
        model = PurchaseOrderItem
        fields = ['id', 'product_id', 'product_name', 'quantity', 'unit', 'unit_price', 'total_price', 'warehouse_id', 'warehouse_name']
        read_only_fields = ['id', 'total_price', 'product_name', 'unit', 'warehouse_name']


class PurchaseOrderSerializer(serializers.ModelSerializer):
    items = PurchaseOrderItemSerializer(many=True, read_only=True)
    purchaser = serializers.CharField(source='purchaser.username', read_only=True)
    
    class Meta:
        model = PurchaseOrder
        fields = ['id', 'order_number', 'supplier', 'purchaser', 'total_amount', 'status', 'remark', 'created_at', 'items']
        read_only_fields = ['id', 'order_number', 'purchaser', 'total_amount', 'created_at']


class CreatePurchaseOrderSerializer(serializers.Serializer):
    supplier = serializers.CharField(max_length=100)
    remark = serializers.CharField(required=False, allow_blank=True)
    items = serializers.ListField(
        child=serializers.DictField(
            child=serializers.CharField(),
            allow_empty=False
        ),
        min_length=1
    )
    
    def validate_items(self, items):
        for item in items:
            if not all(k in item for k in ('product_id', 'quantity', 'unit_price', 'warehouse_id')):
                raise serializers.ValidationError("每个商品项必须包含product_id, quantity, unit_price和warehouse_id")
            
            try:
                product_id = int(item['product_id'])
                if not Product.objects.filter(id=product_id).exists():
                    raise serializers.ValidationError(f"商品ID {product_id} 不存在")
            except (ValueError, TypeError):
                raise serializers.ValidationError("商品ID必须是整数")
                
            try:
                quantity = int(item['quantity'])
                if quantity <= 0:
                    raise serializers.ValidationError("数量必须大于0")
            except (ValueError, TypeError):
                raise serializers.ValidationError("数量必须是整数")
                
            try:
                unit_price = Decimal(str(item['unit_price']))
                if unit_price <= 0:
                    raise serializers.ValidationError("单价必须大于0")
            except (ValueError, TypeError, InvalidOperation):
                raise serializers.ValidationError("单价必须是有效的数字")
                
            try:
                warehouse_id = int(item['warehouse_id'])
                if not Warehouse.objects.filter(id=warehouse_id).exists():
                    raise serializers.ValidationError(f"仓库ID {warehouse_id} 不存在")
            except (ValueError, TypeError):
                raise serializers.ValidationError("仓库ID必须是整数")
                
        return items


class UpdatePurchaseOrderStatusSerializer(serializers.Serializer):
    status = serializers.ChoiceField(choices=['confirmed', 'received', 'cancelled'])
    note = serializers.CharField(required=False, allow_blank=True)